import com.game.User;
import jakarta.servlet.annotation.WebServlet;

import jakarta.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取参数（关键修复点）
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        // 基础参数校验
        if (username == null || username.trim().isEmpty()) {
            request.setAttribute("errorMsg", "用户名不能为空");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username.trim()); // 确保去除空格
        user.setPassword(password); // 注意：实际应加密存储
        user.setEmail(email);

        // 数据库操作
        UserDAO userDAO = new UserDAO();
        try {
            if (userDAO.register(user)) {
                request.getSession().setAttribute("successMsg", "注册成功，请登录");
                response.sendRedirect("login.jsp");
            } else {
                request.setAttribute("errorMsg", "注册失败，请重试");
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            throw new ServletException("数据库操作异常", e);
        }
    }
}